package linuxbox.calendar.servlet;

import java.util.Calendar;
import java.util.Iterator;
import javax.servlet.http.*;
import javax.servlet.ServletOutputStream;

import org.apache.log4j.*;

import linuxbox.BoxStatic;
import linuxbox.common.Action;
import linuxbox.common.BoxSession;
import linuxbox.calendar.logic.BoxCalendar;
import linuxbox.calendar.logic.BoxCalendarEntry;
import linuxbox.util.StringUtil;

/**
 * <p>Title: </p>
 * <p>Description: </p>
 * <p>Copyright: Copyright (c) 2002</p>
 * <p>Company: </p>
 * @author unascribed
 * @version 1.0
 */

public class BoxCalendarSettingsAction
    extends Action
{
  protected static Logger logger = Logger.getLogger(BoxCalendarSettingsAction.class.getName());
  protected static String editJSP = null;
  protected static String viewJSP = null;
  protected static String confirmClearJSP = null;

  public void doAction(HttpSession aSession, BoxSession aBoxSession,
                       HttpServletRequest req, HttpServletResponse resp) throws
      Exception
  {
    String str = req.getParameter("SubmitCancel");
    if (str != null)
    {
      sendFile(viewJSP, req, resp);
      return;
    }

    str = (String) req.getParameter("SubmitEdit");
    if (str != null)
    {
      GetSettings(req, aBoxSession);
      sendFile(editJSP, req, resp);
      return;
    }
    str = (String) req.getParameter("SubmitSave");
    if (str != null)
    {
      SaveSettings(req, aBoxSession);
      sendFile(viewJSP, req, resp);
      return;
    }
    str = (String) req.getParameter("SubmitClear");
    if (str != null)
    {
      sendFile(confirmClearJSP, req, resp);
      return;
    }
    str = (String) req.getParameter("SubmitConfirmedClear");
    if (str != null)
    {
      GetSettings(req, aBoxSession);

      BoxCalendar home = BoxCalendar.getInstance();
      home.clearCalendar(aBoxSession.getID());

      sendFile(editJSP, req, resp);
      return;
    }
    str = (String) req.getParameter("SubmitExport");
    if (str != null)
    {
      exportCalendar(aBoxSession, req, resp);
      return;
    }
    sendFile(viewJSP, req, resp);
  }

  protected void SaveSettings(HttpServletRequest req, BoxSession session)
  {
    try
    {
      String str = (String) req.getParameter("DEFAULT_VIEW");
      session.setConfigString("calendar", "General", "Default View", str);

      str = (String) req.getParameter("TIME_INTERVAL");
      session.setConfigInt("calendar", "General", "Time Interval",
                           Integer.parseInt(str));

      str = (String) req.getParameter("WEEK_START_DAY");
      session.setConfigInt("calendar", "General", "Week Start Day",
                           Integer.parseInt(str));

      str = (String) req.getParameter("WORK_START_HOUR");
      session.setConfigInt("calendar", "General", "Working Hour Start",
                           Integer.parseInt(str));

      str = (String) req.getParameter("WORK_END_HOUR");
      session.setConfigInt("calendar", "General", "Working Hour End",
                           Integer.parseInt(str));

      str = (String) req.getParameter("ENTRIES_PER_PAGE");
      session.setConfigInt("calendar", "Event List", "Entries Per Page",
                           Integer.parseInt(str));

      str = (String) req.getParameter("DST");
      session.setConfigInt("calendar","Date & Time", "DST",
                           Integer.parseInt(str));

      str = (String) req.getParameter("TIMEZONE");
      if (str != null && str.length()>0)
      {
        session.setTimeZone(str);
        Calendar currentDate = (Calendar)req.getSession().getAttribute("calendar.CurDate");
        currentDate.setTimeZone(session.getTimeZone());
      }

      String[] cats = req.getParameterValues("CATEGORIES");
      session.setConfigStrings("calendar", "Event Category", "Categories", cats);
    }
    catch (Exception e)
    {
      //TODOXX: if input data error, should forward to the error page
      if (logger.isDebugEnabled())
      {
        logger.error(e);
      }
    }
  }

  protected void GetSettings(HttpServletRequest req, BoxSession session)
  {
    try
    {
      String str = session.getConfigString("calendar", "General",
                                           "Default View");
      req.setAttribute("DEFAULT_VIEW", str);

      str = session.getConfigString("calendar", "General", "Time Interval");
      req.setAttribute("TIME_INTERVAL", str);

      str = session.getConfigString("calendar", "General", "Week Start Day");
      req.setAttribute("WEEK_START_DAY", str);

      str = session.getConfigString("calendar", "General", "Working Hour Start");
      req.setAttribute("WORK_START_HOUR", str);

      str = session.getConfigString("calendar", "General", "Working Hour End");
      req.setAttribute("WORK_END_HOUR", str);

      int i = session.getConfigInt("calendar", "Event List",
                                   "Entries Per Page");
      req.setAttribute("ENTRIES_PER_PAGE", String.valueOf(i));

      i = session.getConfigInt("calendar", "Date & Time", "DST");
      req.setAttribute("DST", String.valueOf(i));

      str = session.getConfigString("calendar", "Date & Time", "Time Zone");
      req.setAttribute("TIMEZONE", str);

      String[] cats = session.getConfigStrings("calendar", "Event Category",
                                               "Categories", false);
      req.setAttribute("CATEGORIES", cats);
    }
    catch (Exception e)
    {
      if (logger.isDebugEnabled())
      {
        logger.error(e);
      }
    }
  }

  protected void exportCalendar(BoxSession aBoxSession, HttpServletRequest req, HttpServletResponse resp) throws
      Exception
  {
    int tmpYear = -1, tmpMonth = -1, tmpDay = -1;
    String str = req.getParameter("FROM_YEAR");
    if (str != null)
    {
      tmpYear = Integer.parseInt(str);
    }
    str = req.getParameter("FROM_MONTH");
    if (str != null)
    {
      tmpMonth = Integer.parseInt(str);
    }
    str = req.getParameter("FROM_DAY");
    if (str != null)
    {
      tmpDay = Integer.parseInt(str);

    }
    Calendar fromCal = Calendar.getInstance(aBoxSession.getTimeZone());
    fromCal.set(tmpYear, tmpMonth, tmpDay, 0, 0, 0);

    str = req.getParameter("TO_YEAR");
    if (str != null)
    {
      tmpYear = Integer.parseInt(str);
    }
    str = req.getParameter("TO_MONTH");
    if (str != null)
    {
      tmpMonth = Integer.parseInt(str);
    }
    str = req.getParameter("TO_DAY");
    if (str != null)
    {
      tmpDay = Integer.parseInt(str);

    }
    Calendar toCal = Calendar.getInstance(aBoxSession.getTimeZone());
    toCal.set(tmpYear, tmpMonth, tmpDay, 0, 0, 0);

    if (fromCal.after(toCal))
    {
      String msg = "From date > to date!" + str;
      logger.error(msg);
      sendError(msg, req, resp);
      return;
    }

    int format = 1;
    str = req.getParameter("EXPORT_FORMAT");
    if (str != null)
      format = Integer.parseInt(str);
    String strExt = ".csv";
    if (format == 2)
      strExt = ".dba";
    try
    {
      // Get the output stream
      ServletOutputStream out = resp.getOutputStream();
      // Set the content type and disposition
//    resp.setContentType("application/whatever" + "; name=\"" +filename + "\"");
//    resp.setHeader("Content-Disposition","attachment; filename=" + filename + ";");
      resp.setContentType("application/octet-stream; name=\"boxcalendar"+ strExt + "\"");
      resp.setHeader("Content-Disposition", "attachment; filename=boxcalendar" + strExt + ";");
// Write out your data however you'd like

      /*      BufferedInputStream fif = new BufferedInputStream(new FileInputStream(SavedFilename));
          int data;
          while((data = fif.read()) != -1)
          {
            out.write(data);
          }
          fif.close();
       */
      BoxCalendar home = BoxCalendar.getInstance();
      Calendar tmp = fromCal;
      int userid = aBoxSession.getID();

      //header
      outputHeader(out, format);
      while (!tmp.after(toCal))
      {
        Iterator it = home.getAllDayEntries(userid, tmp, userid);
        if (it != null && it.hasNext())
        {
          while (it.hasNext())
          {
             BoxCalendarEntry entry = (BoxCalendarEntry)it.next();
             if (entry != null)
             {
               outputEntry(tmp, out, format, entry);
             }
          }
        }
        it = home.getEntries(userid, tmp, userid);
        if (it != null && it.hasNext())
        {
          while (it.hasNext())
          {
             BoxCalendarEntry entry = (BoxCalendarEntry)it.next();
             if (entry != null)
             {
               outputEntry(tmp, out, format, entry);
             }
          }
        }
        tmp.add(Calendar.DATE, 1);
      }
      out.close();
    }
    catch (Exception e)
    {
      logger.error(e);
      sendError(e.getMessage(), req, resp);
    }
  }

  protected void outputHeader(ServletOutputStream out, int format) throws Exception
  {
    if (format == 1)
    out.println("\"Subject\",\"Start Date\",\"Start Time\",\"End Date\",\"End Time\",\"All day event\",\"Description\"");
  }

  protected void outputEntry(Calendar today, ServletOutputStream out, int format, BoxCalendarEntry entry) throws Exception
  {
    if (format == 1)
    {
      out.print("\"");
      out.print(entry.getSubject());
      out.print("\",\"");
      if (!entry.getIsAllDay())
      {
        if (entry.getRepeat())
          out.print(StringUtil.getDateTimeFormatString(today.getTimeZone(), BoxStatic.SHORT_DATE_FORMAT, today.getTime()));
        else
          out.print(StringUtil.getDateTimeFormatString(today.getTimeZone(), BoxStatic.SHORT_DATE_FORMAT, entry.getFromTime() ));

        out.print("\",\"");
        out.print(StringUtil.getDateTimeFormatString(today.getTimeZone(), BoxStatic.SHORT_TIME_FORMAT, entry.getFromTime() ));
        out.print("\",\"");
        if (entry.getRepeat())
          out.print(StringUtil.getDateTimeFormatString(today.getTimeZone(), BoxStatic.SHORT_DATE_FORMAT, today.getTime()));
        else
          out.print(StringUtil.getDateTimeFormatString(today.getTimeZone(), BoxStatic.SHORT_DATE_FORMAT, entry.getToTime() ));
        out.print("\",\"");
        out.print(StringUtil.getDateTimeFormatString(today.getTimeZone(), BoxStatic.SHORT_DATE_FORMAT, entry.getToTime() ));
      }
      else
      {
        out.print("\",\"\",\"\",\"");
      }
      out.print("\",\"");
      out.print(entry.getIsAllDay());
      out.print("\",\"");
      out.print(entry.getDescription());
      out.print("\"");
      out.println();
    }
  }

  public void setEditJSP(String str)
  {
    editJSP = str;
  }

  public void setViewJSP(String str)
  {
    viewJSP = str;
  }

  public void setConfirmClearJSP(String str)
  {
    confirmClearJSP = str;
  }
}
